<?php
/*  
 * @author ada <124541939@qq.com>
 * @version 1.0
 * @created on 2018/07/15
 * @package common
 */
namespace app\sgwy\controller;  
use app\sgwy\logic\LogLogic; 
use app\sgwy\logic\UsersLogic; 
use think\Controller;  
 
class BaseCommon extends Controller {  
  
    const SIGN_KEY = "ehSDsdfdsfdsHSDF9876fWdsfdsga9"; //签名key
    protected $request; 
    protected $failError;
    protected $make_sign = null; 
    protected $sign = null;
    protected $logLogic = null;

    public function __construct(){
        $this->failError=config('api_param'); 
        $this->getMethod(); 
        //获取请求参数
        $this->request = self::requestInfo();
        $this->sign = $this->request['sign'];
        $this->logLogic = new LogLogic();
  
        //记录请求log
       $this->log(array("request_url"=>"http://".$_SERVER['HTTP_HOST']."/".$_SERVER['REQUEST_URI'],"request_data"=>$this->request));

        //验证签名
        // self::signcheck(); 
 
    }

    /**
     * 封装ajax的返回结果
     *
     * @param int $status 状态码
     * @param string $message 提示信息
     * @param array $data 返回值
     *
     * @return mixed
     */   
    public function ajaxReturn($message = array(), $return_arr = false)
    {
        header('Content-Type:application/json; charset=utf-8');

        //查询用户token信息
        if(isset($this->request['userId']) && isset($this->request['token']) && $this->request['userId'] && $this->request['token']){
            $user_token = $this->getUserToken(array("user_id"=>$this->request['userId']));
            $message['token'] = $user_token['token'];
            $message['user_id'] = $user_token['user_id'];
        }

        $message['deviceCode'] = (isset($this->request['deviceCode']) && $this->request['deviceCode']) ? $this->request['deviceCode'] : "";
        $message['sign'] = (isset($this->request['sign']) && $this->request['sign']) ? $this->request['sign'] : "";
        $message['version'] = (isset($this->request['version']) && $this->request['version']) ? $this->request['version'] : "";

        //记录返回log
        $this->log(array("request_url"=>"http://".$_SERVER['HTTP_HOST']."/".$_SERVER['REQUEST_URI'],"request_data"=>$this->request,"return_data"=>$message)); 

        if($return_arr){
            echo json_encode($message, JSON_FORCE_OBJECT);
        }else {
            echo json_encode($message);
        }
        exit;
    }

    /**
     *
     * 处理请求参数
     */
    protected function requestInfo(){ 
        $data = $_POST; 
        if(!$data){
            $this->ajaxReturn($this->failError['QQBWFF']);  
        }
        return $data;
    }


    /**
     *
     * 获取接口请求方式
     */
    public function getMethod(){ 
        $request_type = $_SERVER['REQUEST_METHOD'];
        if($request_type != 'POST') 
            $this->ajaxReturn($this->failError['FFQQ']);   
        return;
    }

    /**
     *
     * 处理验证签名
     */
    protected function signdata(){
        $request = $this->request; 
        if(!isset($request['inteface']) || !$request['inteface']){
            $this->ajaxReturn($this->failError['JKLXCW']);
        }

        if(!isset($request['deviceCode']) || !isset($request['sign']) || !isset($request['version']) || !isset($request['deviceType']) || !isset($request['timeStamp'])){
            $this->ajaxReturn($this->failError['QQCSCW']); 
        }

        if(!isset($request['source']) || !$request['source']){
            $this->ajaxReturn($this->failError['QDBNWK']);  
        } 

        $data = array();
        if($request){
            foreach($request as $k=>$v){
                if(is_array($v)){
                    $data[$k] = json_encode($v, JSON_UNESCAPED_UNICODE);
                }elseif(isset($v) && $v != "" && $k != 'sign'){
                    $data[$k] = $this->chineseIcReplace($v);
                }
            }
        }

        $request_str = "";
        if($data){
            ksort($data, SORT_STRING);
            $data['key'] = self::SIGN_KEY;
            foreach($data as $k=>$v){
                $request_str .= $k."=".$v."&";
            }
        }
        $request_str = substr($request_str, 0, -1);
        return MD5($request_str);
    }

    public function chineseIcReplace($str){
        return preg_replace_callback("#\\\u([0-9a-f]{4})#i", function($r){
            return iconv('UCS-2BE', 'UTF-8', pack('H4', $r[1]));
            }, trim($str));
    }

    /**
     *
     * 验证签名
     */
    protected function signcheck(){
        $this->make_sign = self::signdata();  
        if($this->make_sign != $this->sign){
            $this->ajaxReturn($this->failError['YQSB']);
        }

        if($this->request){
            foreach($this->request as $k=>$v){
                if(is_array($v)){
                    if($v){
                        foreach($v as $k1=>$v1){
                            $v[$k1] = $this->filter_keyword($v1);
                        }
                    }
                    $this->request[$k] = $v;
                }else{
                    $this->request[$k] = $this->filter_keyword($v);
                }
            }
        }
    }

    /**
     *
     * 记录log
     */
    protected function log($message){
        if(empty($message)) return false;
        if(is_array($message)) $message=json_encode($message,JSON_UNESCAPED_UNICODE);
        $addData=[
            'action'=>"sgwy.".request()->controller(),
            'func'=>request()->action(), 
            'content'=>$message,
        ]; 
        $this->logLogic->addLog($addData);
    }


    /**
     * @param $string
     * @return mixed
     * 过滤特殊字符
     */
    private function filter_keyword( $string ) {
        $keyword = 'select|insert|update|delete|\'|*|\.\.\/|\.\/|union|into|load_file|outfile| |#|$';
        $arr = explode( '|', $keyword );
        $result = str_ireplace( $arr, '', $string );
        return $result;
    }

    /**
     * 空操作
     * 404 
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Xml
     */
    public function _empty()
    {  
        $this->ajaxReturn(4000,'empty method!');
    }

    /**
     * @param $data
     * 获取用户token
     */
    public function getUserToken($data){
        $deviceType = $this->request['deviceType'];
        $mobile_type = "other";
        if($deviceType == "A"){
            $mobile_type = "android";
        }elseif($deviceType == "I"){
            $mobile_type = "ios";
        }elseif($deviceType == "H"){
            $mobile_type = "h5";
        }elseif($deviceType == "A"){
            $mobile_type = "app";
        }

        //存储用户token
        $t_data = array();
        $t_data['user_id'] = $data['user_id'];
        $t_data['mobile_type'] = $mobile_type;
        $t_data['inteface_type'] = $this->request['deviceType'];
        $t_data['devicecode'] = $this->request['deviceCode'];

        //查询是否存在客户token
        $_user_token = new UsersLogic(); 
        $user_token = $_user_token->getUserToken($t_data);
        return $user_token;
    }
}
